<template>
  <div class="homework-page">
    <el-card>
      <el-form :inline="true" :model="searchForm" class="search-form-container mb-6 bg-gray-50 p-4 rounded-lg shadow-sm">
        <div class="search-inputs-actions">
          <div class="flex items-center flex-wrap gap-x-4 gap-y-2">
            <el-form-item label="" class="mb-0">
              <el-input v-model="searchForm.title" placeholder="作业标题" style="width: 150px;" clearable />
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-input v-model="searchForm.courseId" placeholder="课程ID" style="width: 120px;" clearable />
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-select v-model="searchForm.autoGrade" placeholder="批改方式" style="width: 120px;" clearable>
                <el-option label="自动批改" :value="true" />
                <el-option label="手动批改" :value="false" />
              </el-select>
            </el-form-item>
            <el-form-item class="mb-0">
              <el-button @click="handleSearch" class="gradient-purple-blue-button">查询</el-button>
              <el-button @click="resetSearch" class="gradient-blue-cyan-button" style="margin-left: 8px;">重置</el-button>
            </el-form-item>
          </div>

          <div class="flex items-center gap-x-4">
            <el-button @click="openDialog()" class="gradient-blue-toggle-button">发布作业</el-button>
            <el-button @click="toggleView" class="gradient-blue-toggle-button">
              {{ isCardView ? '切换为列表' : '切换为卡片' }}
            </el-button>
          </div>
        </div>
      </el-form>

      <el-row :gutter="20" class="chart-section">
        <el-col :span="8">
          <el-card>
            <h3>各课程作业数量</h3>
            <div ref="courseAssignmentChartRef" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <h3>批改方式占比</h3>
            <div ref="autoGradeChartRef" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <h3>作业发布趋势</h3>
            <div ref="publishTrendChartRef" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <div v-loading="loading">
        <template v-if="isCardView">
          <el-row :gutter="20" class="assignment-card-grid">
            <template v-if="filteredAssignmentList.length > 0">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in filteredAssignmentList" :key="item.id">
                <el-card class="assignment-card">
                  <div class="assignment-card-content">
                    <h4 class="assignment-card-title" :title="item.title">{{ item.title }}</h4>
                    <p class="assignment-card-info"><span class="info-label">课程ID:</span> {{ item.courseId }}</p>
                    <p class="assignment-card-info"><span class="info-label">批改方式:</span>
                      <el-tag :type="item.autoGrade ? 'success' : 'info'" size="small">{{ item.autoGrade ? '自动' : '手动' }}</el-tag>
                    </p>
                    <p class="assignment-card-info"><span class="info-label">发布于:</span> {{ dateFormatter(null, null, item.publishTime) }}</p>
                    <p class="assignment-card-info"><span class="info-label">截止于:</span> {{ dateFormatter(null, null, item.deadline) }}</p>
                    <p class="assignment-card-info" v-if="item.filePath">
                        <span class="info-label">附件:</span>
                        <el-link type="primary" :underline="false" @click.stop="downloadFile(item.filePath)">
                            下载附件
                        </el-link>
                    </p>
                  </div>
                  <div class="assignment-card-actions">
                    <el-button size="mini" @click="editAssignment(item)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="openDeleteDialog(item)" class="light-red-button">删除</el-button>
                  </div>
                </el-card>
              </el-col>
            </template>
            <div v-else class="empty-assignments">
              <el-empty description="暂无作业，请发布或调整搜索条件"></el-empty>
            </div>
          </el-row>
        </template>

        <template v-else>
          <el-table :data="filteredAssignmentList" border style="width: 100%; margin-top: 20px;">
            <el-table-column prop="title" label="作业标题" />
            <el-table-column prop="courseId" label="课程ID" />
            <el-table-column prop="deadline" label="截止日期" :formatter="dateFormatter" />
            <el-table-column prop="publishTime" label="发布时间" :formatter="dateFormatter" />
            <el-table-column prop="autoGrade" label="自动批改">
              <template #default="scope">
                <el-tag v-if="scope.row.autoGrade" type="success">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <el-button type="primary" size="small" @click="editAssignment(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="openDeleteDialog(scope.row)" class="light-red-button">删除</el-button>
                <el-button v-if="scope.row.filePath" size="small" @click="downloadFile(scope.row.filePath)">附件</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="editMode ? '编辑作业' : '发布作业'" width="500px" @close="resetForm">
      <el-form :model="form" label-width="90px" ref="formRef">
        <el-form-item label="课程ID" prop="courseId" required>
          <el-input v-model.number="form.courseId" placeholder="课程ID" />
        </el-form-item>
        <el-form-item label="作业标题" prop="title" required>
          <el-input v-model="form.title" placeholder="作业标题" />
        </el-form-item>
        <el-form-item label="作业内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="作业内容" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime" required>
          <el-date-picker v-model="form.publishTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择发布时间" style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline" required>
          <el-date-picker v-model="form.deadline" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择截止时间" style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="自动批改" prop="autoGrade" required>
          <el-switch v-model="form.autoGrade" />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload :show-file-list="false" :before-upload="beforeUpload" :on-change="onFileChange" :auto-upload="false">
            <el-button>选择文件</el-button>
            <span v-if="form.fileName" style="margin-left:8px;">{{ form.fileName }}</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
    
    <el-dialog title="确认删除" v-model="showDeleteDialog" width="300px">
      <div>确定要删除该作业记录吗？</div>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="deleteRecord" class="light-red-button">删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import assignmentService from '../../services/assignmentService';
import { FILE_BASE_URL } from '../../services/config';
import * as echarts from 'echarts';

const allAssignmentList = ref([]); // 存储所有从后端获取的作业数据
const filteredAssignmentList = ref([]); // 存储用于展示的、经过筛选的作业数据
const loading = ref(false);
const dialogVisible = ref(false);
const showDeleteDialog = ref(false);
const editMode = ref(false);
const currentDeleteId = ref(null);

const form = ref({ id: null, courseId: '', title: '', content: '', publishTime: '', deadline: '', autoGrade: false, file: null, fileName: '', filePath: '' });
const formRef = ref();

const searchForm = reactive({ title: '', courseId: '', autoGrade: null });
const isCardView = ref(true); // 默认卡片视图

// ECharts 实例
const courseAssignmentChartRef = ref(null);
const autoGradeChartRef = ref(null);
const publishTrendChartRef = ref(null);
let courseAssignmentChart = null;
let autoGradeChart = null;
let publishTrendChart = null;

// 加载数据
async function loadList() {
  loading.value = true;
  try {
    const res = await assignmentService.getAllAssignments();
    allAssignmentList.value = res.status === 0 ? res.data : [];
    handleSearch(); // 初始加载后应用一次（空的）搜索条件
  } catch (error) {
    ElMessage.error('获取作业列表失败');
    allAssignmentList.value = [];
    filteredAssignmentList.value = [];
  } finally {
    loading.value = false;
  }
}

// 搜索功能
function handleSearch() {
  let filtered = [...allAssignmentList.value];

  if (searchForm.title) {
    filtered = filtered.filter(item => item.title.includes(searchForm.title));
  }
  if (searchForm.courseId) {
    filtered = filtered.filter(item => String(item.courseId).includes(searchForm.courseId));
  }
  if (searchForm.autoGrade !== null && searchForm.autoGrade !== '') {
    filtered = filtered.filter(item => item.autoGrade === searchForm.autoGrade);
  }

  filteredAssignmentList.value = filtered;
  updateAllCharts();
}

// 重置搜索
function resetSearch() {
  searchForm.title = '';
  searchForm.courseId = '';
  searchForm.autoGrade = null;
  handleSearch();
}

// 视图切换
const toggleView = () => {
  isCardView.value = !isCardView.value;
};

// --- 表单与弹窗逻辑 ---
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form.value, { id: null, courseId: '', title: '', content: '', publishTime: '', deadline: '', autoGrade: false, file: null, fileName: '', filePath: '' });
}

function openDialog() {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
}

function editAssignment(row) {
  editMode.value = true;
  resetForm();

  const publishTimeAsDate = parseDate(row.publishTime);
  const deadlineAsDate = parseDate(row.deadline);

  Object.assign(form.value, {
    id: row.id,
    courseId: row.courseId,
    title: row.title,
    content: row.content,
    publishTime: publishTimeAsDate ? dateFormatter(null, null, publishTimeAsDate, 'YYYY-MM-DD HH:mm:ss') : null,
    deadline: deadlineAsDate ? dateFormatter(null, null, deadlineAsDate, 'YYYY-MM-DD HH:mm:ss') : null,
    autoGrade: row.autoGrade,
    file: null,
    fileName: row.filePath ? row.filePath.split('/').pop() : '',
    filePath: row.filePath || ''
  });
  dialogVisible.value = true;
}

// --- 文件上传逻辑 ---
function beforeUpload(rawFile) {
  form.value.file = rawFile;
  form.value.fileName = rawFile.name;
  return false;
}
function onFileChange(uploadFile) {
  if (uploadFile && uploadFile.raw) {
    form.value.file = uploadFile.raw;
    form.value.fileName = uploadFile.name;
  }
}
function getFileUrl(filePath) {
  if (!filePath) return '';
  if (filePath.startsWith('http')) return filePath;
  return FILE_BASE_URL + filePath;
}
function downloadFile(filePath) {
  if (filePath) window.open(getFileUrl(filePath), '_blank');
}


// --- CRUD 操作 ---
async function submitForm() {
  await formRef.value.validate(async (valid) => {
    if (!valid) return;

    const formData = new FormData();
    if (editMode.value) {
      formData.append('id', form.value.id);
    }
    formData.append('courseId', String(form.value.courseId));
    formData.append('title', form.value.title);
    formData.append('content', form.value.content || '');
    formData.append('publishTime', form.value.publishTime);
    formData.append('deadline', form.value.deadline);
    formData.append('autoGrade', String(form.value.autoGrade));
    if (form.value.file) {
      formData.append('filePath', form.value.file);
    }

    try {
      if (editMode.value) {
        await assignmentService.updateAssignment(formData);
        ElMessage.success('作业更新成功');
      } else {
        await assignmentService.publishAssignment(formData);
        ElMessage.success('作业发布成功');
      }
      dialogVisible.value = false;
      await loadList();
    } catch (err) {
      console.error('操作失败:', err);
      ElMessage.error(err.message || '操作失败，请查看控制台日志');
    }
  });
}

function openDeleteDialog(row) {
  currentDeleteId.value = row.id;
  showDeleteDialog.value = true;
}

async function deleteRecord() {
    try {
        await assignmentService.deleteAssignment(currentDeleteId.value);
        ElMessage.success('删除成功');
        showDeleteDialog.value = false;
        await loadList();
    } catch(err) {
        ElMessage.error('删除失败');
    }
}


// --- 日期处理 ---
function parseDate(cellValue) {
  if (!cellValue) return null;
  let dateObj;
  if (Array.isArray(cellValue)) {
    const [y, m, d, hh, mm, ss] = cellValue;
    dateObj = new Date(y, (m || 1) - 1, d || 1, hh || 0, mm || 0, ss || 0);
  } else if (typeof cellValue === 'number') {
    dateObj = new Date(cellValue);
  } else if (typeof cellValue === 'string') {
    dateObj = new Date(cellValue);
  } else if (cellValue instanceof Date) {
    dateObj = cellValue;
  } else {
    return null;
  }
  return isNaN(dateObj.getTime()) ? null : dateObj;
}

function dateFormatter(row, column, cellValue, format = 'YYYY-MM-DD HH:mm') {
  const dateObj = parseDate(cellValue);
  if (!dateObj) return '';

  const y = dateObj.getFullYear();
  const m = String(dateObj.getMonth() + 1).padStart(2, '0');
  const d = String(dateObj.getDate()).padStart(2, '0');
  const hh = String(dateObj.getHours()).padStart(2, '0');
  const mm = String(dateObj.getMinutes()).padStart(2, '0');
  const ss = String(dateObj.getSeconds()).padStart(2, '0');

  if (format === 'YYYY-MM-DD HH:mm:ss') {
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
  }
  return `${y}-${m}-${d} ${hh}:${mm}`;
}

// --- ECharts 渲染逻辑 ---
function initCharts() {
    if (courseAssignmentChartRef.value) courseAssignmentChart = echarts.init(courseAssignmentChartRef.value);
    if (autoGradeChartRef.value) autoGradeChart = echarts.init(autoGradeChartRef.value);
    if (publishTrendChartRef.value) publishTrendChart = echarts.init(publishTrendChartRef.value);
    updateAllCharts();

    window.addEventListener('resize', () => {
        courseAssignmentChart?.resize();
        autoGradeChart?.resize();
        publishTrendChart?.resize();
    });
}

function updateAllCharts() {
    const data = filteredAssignmentList.value;
    if (!data) return;
    updateCourseAssignmentChart(data);
    updateAutoGradeChart(data);
    updatePublishTrendChart(data);
}

function updateCourseAssignmentChart(data) {
  if (!courseAssignmentChart) return;
  const courseCount = data.reduce((acc, item) => {
    const courseId = item.courseId || '未知课程';
    acc[courseId] = (acc[courseId] || 0) + 1;
    return acc;
  }, {});
  const courseIds = Object.keys(courseCount);
  const counts = Object.values(courseCount);
  courseAssignmentChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: [{ type: 'category', data: courseIds, axisTick: { alignWithLabel: true } }],
    yAxis: [{ type: 'value', minInterval: 1 }],
    series: [{ name: '作业数量', type: 'bar', barWidth: '60%', data: counts, itemStyle: { color: '#5470C6' } }]
  });
}

function updateAutoGradeChart(data) {
  if (!autoGradeChart) return;
  const autoGradeCount = data.reduce((acc, item) => {
    item.autoGrade ? acc.auto++ : acc.manual++;
    return acc;
  }, { auto: 0, manual: 0 });
  autoGradeChart.setOption({
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)' },
    legend: { top: '5%', left: 'center' },
    series: [{
      name: '批改方式',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: { show: false, position: 'center' },
      emphasis: { label: { show: true, fontSize: 20, fontWeight: 'bold' } },
      labelLine: { show: false },
      data: [
        { value: autoGradeCount.auto, name: '自动批改', itemStyle: { color: '#91CC75' } },
        { value: autoGradeCount.manual, name: '手动批改', itemStyle: { color: '#FAC858' } },
      ]
    }]
  });
}

function updatePublishTrendChart(data) {
  if (!publishTrendChart) return;
  const trendData = data.reduce((acc, item) => {
    const dateObj = parseDate(item.publishTime);
    if(dateObj) {
      const month = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}`;
      acc[month] = (acc[month] || 0) + 1;
    }
    return acc;
  }, {});
  const sortedMonths = Object.keys(trendData).sort();
  const counts = sortedMonths.map(month => trendData[month]);
  publishTrendChart.setOption({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', boundaryGap: false, data: sortedMonths },
    yAxis: { type: 'value', minInterval: 1 },
    series: [{ data: counts, type: 'line', smooth: true, name: '发布数量', itemStyle: { color: '#EE6666' } }],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  });
}


// --- 生命周期钩子 ---
onMounted(async () => {
  await loadList();
  initCharts();
});

watch(allAssignmentList, (newList) => {
    if (newList) {
        handleSearch();
    }
}, { deep: true });

</script>

<style scoped>
/* 复制自实训管理页面的所有样式，并做微调 */
.homework-page {
  padding: 32px 24px;
  background: #f8f9fb;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.flex-wrap {
  flex-wrap: wrap;
}

.gap-x-4 {
  column-gap: 1rem;
}

.gap-y-2 {
  row-gap: 0.5rem;
}

.search-inputs-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  gap: 10px;
}

.search-form-container {
  background-color: #f9fafb;
  padding: 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 1.5rem;
}

.el-form-item.mb-0 {
  margin-bottom: 0 !important;
}

.chart-section {
  margin-top: 20px;
}
.chart-section h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #303133;
    text-align: center;
}


/* --- 自定义按钮样式 --- */
.gradient-purple-blue-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #8b5dbd, #548ee0) !important;
  border-color: #8b5dbd !important;
  transition: all 0.3s ease;
}
.gradient-purple-blue-button:hover,
.gradient-purple-blue-button:focus {
  background-image: linear-gradient(to right, #9d70d1, #69a7f3) !important;
  border-color: #9d70d1 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.gradient-blue-cyan-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #548ee0, #38afb5) !important;
  border-color: #548ee0 !important;
  transition: all 0.3s ease;
}
.gradient-blue-cyan-button:hover,
.gradient-blue-cyan-button:focus {
  background-image: linear-gradient(to right, #69a7f3, #4fd3d8) !important;
  border-color: #69a7f3 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.gradient-blue-toggle-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #3f51b5, #2196f3) !important;
  border-color: #3f51b5 !important;
  transition: all 0.3s ease;
}
.gradient-blue-toggle-button:hover,
.gradient-blue-toggle-button:focus {
  background-image: linear-gradient(to right, #5c6bc0, #42a5f5) !important;
  border-color: #5c6bc0 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.light-red-button {
  background-color: #FEE2E2 !important;
  color: #EF4444 !important;
  border-color: #FEE2E2 !important;
}
.light-red-button:hover,
.light-red-button:focus {
  background-color: #FECDCD !important;
  border-color: #FECDCD !important;
}

/* --- 作业卡片视图样式 --- */
.assignment-card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px 0; /* 垂直间距，水平间距由 el-col 控制 */
  margin-top: 20px;
  padding-bottom: 20px;
}

.assignment-card {
  min-height: 250px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #ffffff;
  border: 1px solid #e9e9e9;
  /* 为 el-col 的 gutter 留出空间 */
  margin: 0 10px;
}

.assignment-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.assignment-card-content {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.assignment-card-title {
  font-size: 1.1em;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  height: 2.8em;
}

.assignment-card-info {
  font-size: 0.9em;
  color: #666;
  margin-bottom: 0;
  line-height: 1.4;
  display: flex;
  align-items: center;
}

.assignment-card-info .info-label {
  font-weight: 500;
  color: #444;
  margin-right: 5px;
  flex-shrink: 0;
}

.assignment-card-actions {
  padding: 10px 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  background-color: #fafafa;
}

.assignment-card-actions .el-button {
  min-width: unset;
  padding: 7px 12px;
  font-size: 0.85em;
}

.empty-assignments {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
</style>